import {
  PlusOutlined,
} from '@ant-design/icons';
import {
  Button,
  message,
  Drawer,
  FormInstance,
  Popconfirm,
  Image,
  Tag,
} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormUploadButton, ProFormSelect,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {
  removeData,
  dataList,
  addData,
  updateData,
  loadData, loadSelectTag,
} from './service';
import type {DocumentBody, DocumentListItem, DocumentListPagination} from './data';
import 'moment/locale/zh-cn';

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: DocumentBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');
  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: DocumentListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData(selectedRows.map((row) => row.documentId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const submitCheckFile = (values: DocumentBody, fileName: string, dataName: string) => {
  if (values[fileName]) {
    let file = values[fileName][0];
    values[dataName] = file?.response?.data?.url || file.url;
  }
};

const requestTag = async () => {
  return loadSelectTag().then(({data}) => {
    return data;
  });
};
const DocumentPage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<DocumentListItem>();
  const columns: ProColumns<DocumentListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        return [
          <a
            key="view"
            onClick={() => {
              formRef.current?.resetFields();
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>,
          <a
            key="edit"
            onClick={() => {
              formRef.current?.resetFields();
              console.log(record);
              setCurrentRow(record);
              setEditMode(true);
              handleModalVisible(true);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="delete"
            okButtonProps={{danger: true}}
            title={`删除后无法恢复,确认删除?`}
            onConfirm={async () => {
              setCurrentRow(record);
              await handleRemove([record]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <a> 删除 </a>
          </Popconfirm>,
        ];

      },
    },
    {
      title: '文件名称',
      dataIndex: 'documentName',
    },
    {
      title: '文件',
      hideInSearch: true,
      dataIndex: 'documentFile',
      render: (_, record) => (
        <a href={record.documentFile} target={"_blank"}>
          查看文件
        </a>
      ),
    },
    {
      title: '标签',
      dataIndex: 'tags',
      request: requestTag,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        mode: 'multiple',
      },
      render: (_, record) => (
        <>
          {record?.tagNames?.map((name, index) => (
            <Tag key={name + index + record.documentId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      title: '创建时间',
      sorter: true,
      align: 'center',
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // @ts-ignore
    onChange({file}) {
      if (file.status === 'done' && file.response.code === 200) {
        formRef.current?.setFieldsValue({
          documentName: file.name,
        });
      }
    },
    name: 'file',
    max: 1,
  };
  return (
    <PageContainer waterMarkProps={{content: ''}}>
      <ProTable<DocumentListItem, DocumentListPagination>
        headerTitle={'文件列表'}
        actionRef={actionRef}
        rowKey="documentId"
        search={{
          labelWidth: 120,
        }}
        options={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditMode(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={dataList}
        columns={columns}
      />
      <ModalForm<DocumentBody>
        title={currentRow?.documentId || 0 > 0 ? '编辑文件' : '新建文件'}
        formRef={formRef}
        layout={'horizontal'}
        labelCol={{span: 4}}
        wrapperCol={{span: 18}}
        visible={createModalVisible}
        onValuesChange={(changedValues) => {
          if (changedValues && changedValues.hasOwnProperty('dateRange')) {
            formRef.current?.setFieldsValue({
              startTime: changedValues.dateRange[0] + '',
            });
            formRef.current?.setFieldsValue({endTime: changedValues.dateRange[1] + ''});
            formRef.current?.setFieldsValue({documentTime: changedValues.dateRange[0] + "至" + changedValues.dateRange[1]});
          }
          console.log(changedValues);
        }}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
        modalProps={{destroyOnClose: true, maskClosable: false}}
        onFinish={async (value) => {
          console.log(value);
          submitCheckFile(value, 'documentFileData', 'documentFile');
          const success = await handleAdd(value, editMode);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              // @ts-ignore
              actionRef.current?.reloadAndRest();
            }
          }
        }}
        request={async (param) => {
          console.log(param);
          if (param.documentId > 0) {
            const {data} = await loadData(param as DocumentBody);
            if (data.tags) data.tagList = data.tags;
            if (data.documentFile)
              data.documentFileData = [
                {
                  url: data.documentFile,
                  name: '文件依据',
                  status: 'done',
                },
              ];
            return data;
          } else {
            return new Promise<DocumentBody>((resolve) => {
              resolve({
                documentId: 0,
              });
            });
          }
        }}
        params={{...currentRow}}
      >
        <ProFormText hidden name="documentId"/>
        <ProFormUploadButton rules={[{required: true}]}
                             name="documentFileData"
                             label="上传文件"
                             max={1}
                             fieldProps={{...uploadProps}}
                             action="/v2/enterprise/upload/document"/>

        <ProFormText rules={[{required: true}]} label={'文件名'} name="documentName"/>
        <ProFormSelect
          name="tagList"
          label="文件标签"
          mode={'tags'}
          request={requestTag}
          extra={'没有合适的标签可以直接输入'}
          placeholder="请选择文件标签，没有合适的标签可以直接输入"
          rules={[{required: true, message: '请文件标签!'}]}
        />
      </ModalForm>

      <Image
        width={200}
        style={{display: 'none'}}
        src={previewData.image}
        preview={{
          visible: previewData.visible,
          src: previewData.image,
          onVisibleChange: (value) => {
            setPreviewData({image: previewData.image, title: '', visible: value});
          },
        }}
      />
      <Drawer
        width={800}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.documentId && (
          <ProDescriptions<DocumentBody>
            column={1}
            bordered={true}
            title={'文件详情'}
            // @ts-ignore
            request={loadData}
            // layout={'vertical'}
            params={currentRow}
            columns={columns as ProDescriptionsItemProps<DocumentBody>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default DocumentPage;
